<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示区域 -->
      <el-alert center title="注意：只允许为第三级分类设置相关参数" type="info" show-icon :closable="false"></el-alert>
      <el-steps align-center :space="300" :active="activeIndex" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="editFormRef"
        label-position="top"
        label-with="100px"
        :model="editForm"
        :rules="editFormRules"
      >
        <el-tabs
          :tab-position="'left'"
          @tab-click="tabClick"
          v-model="activeTab"
          :before-leave="beforeTabLeave"
          style="height: auto;"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model.trim="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="editForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="editForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="editForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <Cascader
                ref="goodsCateCascader"
                @handle="handle"
                :type="3"
                :cateIdArr="editForm.goods_cat"
              ></Cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTableData">
              <el-checkbox-group @change="checkBoxChange" v-model="item.attr_value">
                <el-checkbox
                  :label="val"
                  border
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2" style="height: 40%;">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in onlyTableData">
              <el-input v-model.trim="item.attr_value"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :headers="headersObj"
              :action="uploadUrl"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="editForm.goods_introduce"
              :options="editorOption"
            />
            <el-button type="primary" @click="updateGoods">编辑商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <img :src="previewSrc" class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import Cascader from './Cascader.vue'
export default {
  props: ['id'],
  data() {
    return {
      activeIndex: 0,
      activeTab: '0',
      editForm: {
        goods_id: '',
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '2333',
        attrs: []
      },
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      manyTableData: [],
      onlyTableData: [],
      fileList: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewSrc: '',
      imgDialogVisible: false,
      editorOption: {
        theme: 'snow'
      }
    }
  },
  methods: {
    async tabClick(tab, event) {
      this.activeIndex = parseInt(this.activeTab)
      // 当商品参数面板有数据时，不刷新当前面板数据
      if (this.activeIndex === 1) {
        if (this.manyTableData.length > 0) {
          return
        }
        // 刷新商品参数面板数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          if (item.attr_vals.trim()) {
            item.attr_vals = item.attr_vals.trim().split(',')
          } else {
            item.attr_vals = []
          }
          this.editForm.attrs.forEach(item1 => {
            if (item1.attr_id === item.attr_id) {
              item.attr_value = item1.attr_value
            }
          })
          if (Object.prototype.hasOwnProperty.call(item, 'attr_value')) {
            if (item.attr_value === '') {
              item.attr_value = []
            }
          } else {
            item.attr_value = []
          }
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === 2) {
        // 当商品属性面板有数据时，不刷新当前面板数据
        if (this.onlyTableData.length > 0) {
          return
        }
        // 刷新商品属性面板数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          if (item.attr_vals.trim()) {
            item.attr_vals = item.attr_vals.trim().split(',')
          } else {
            item.attr_vals = []
          }
          this.editForm.attrs.forEach(item1 => {
            if (item1.attr_id === item.attr_id) {
              item.attr_value = item1.attr_value
            }
          })
          if (!item.attr_value) {
            item.attr_value = ''
          }
        })
        this.onlyTableData = res.data
      }
    },
    // 修改商品分类后，重置商品参数，商品属性面板数据
    handle(value) {
      this.editForm.goods_cat = value
      this.manyTableData = []
      this.onlyTableData = []
      if (this.editForm.goods_cat.length !== 3) {
        this.editForm.goods_cat = []
        this.$refs.goodsCateCascader.selectedKeys = []
      }
    },
    checkBoxChange(val) {
      console.log(val)
    },
    beforeTabLeave(activeName, oldActiveName) {
      for (const key in this.editForm) {
        if (!this.editForm[key] || this.editForm.goods_cat.length !== 3) {
          this.$message.error('请先填写基本信息')
          return false
        }
      }
    },
    handleSuccess(response, file, fileList) {
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.editForm.pics.push(picInfo)
    },
    handleRemove(file, fileList) {
      const filePath = file.url
      const index = this.editForm.pics.findIndex(item => {
        if (item.pics_sma_url === filePath) {
          return true
        }
      })
      this.editForm.pics.splice(index, 1)
    },
    handlePreview(file) {
      this.previewSrc = file.response.data.url
      this.imgDialogVisible = true
    },
    updateGoods() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        this.editForm.attrs = []
        this.manyTableData.forEach(item => {
          if (item.attr_value.length === 0) {
            return
          }
          const attrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_value.join(',')
          }
          this.editForm.attrs.push(attrInfo)
        })
        this.onlyTableData.forEach(item => {
          if (!item.attr_value) {
            return
          }
          const attrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_value
          }
          this.editForm.attrs.push(attrInfo)
        })
        this.editForm.goods_cat = this.editForm.goods_cat.join(',')
        const { data: res } = await this.$http.put(
          `goods/${this.editForm.goods_id}`,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    },
    async getGoodsInfo() {
      // 初始化商品数据
      const { data: res } = await this.$http.get(`goods/${this.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm.goods_id = res.data.goods_id
      this.editForm.goods_name = res.data.goods_name
      this.editForm.goods_price = res.data.goods_price
      this.editForm.goods_weight = res.data.goods_weight
      this.editForm.goods_number = res.data.goods_number
      this.editForm.goods_introduce = res.data.goods_introduce
      res.data.pics.forEach(item => {
        item.pic = item.pics_sma
      })
      this.editForm.pics = res.data.pics
      res.data.attrs.forEach(item => {
        if (item.attr_sel === 'many') {
          if (item.attr_vals.trim() && item.attr_value.trim()) {
            item.attr_vals = item.attr_vals.trim().split(',')
            item.attr_value = item.attr_value.trim().split(',')
          }
        }
      })
      this.editForm.attrs = res.data.attrs
      this.editForm.goods_cat.push(res.data.cat_one_id)
      this.editForm.goods_cat.push(res.data.cat_two_id)
      this.editForm.goods_cat.push(res.data.cat_three_id)
      this.editForm.pics.forEach(item => {
        const fileInfo = {
          url: item.pics_sma_url
        }
        this.fileList.push(fileInfo)
      })
    }
  },
  computed: {
    cateId() {
      if (this.editForm.goods_cat.length === 3) {
        return this.editForm.goods_cat[2]
      }
      return null
    },
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  components: {
    Cascader
  },
  created() {
    this.getGoodsInfo()
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 30% !important;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>
